package bg.btanev.eightyfour.gwtfacade.commandhandler;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.Validate;

import bg.btanev.eightyfour.domain.Target;
import bg.btanev.eightyfour.service.AnalyticsService;
import bg.btanev.eightyfour.service.TargetService;
import bg.btanev.eightyfour.shared.analytics.WeekDayActivityStat;
import bg.btanev.eightyfour.shared.command.CommandResult;
import bg.btanev.eightyfour.shared.command.stat.StatCommandInput;
import bg.btanev.eightyfour.shared.command.stat.StatWeekDayActivityCommand;
import bg.btanev.eightyfour.shared.dto.TargetDto;

/**
 *
 * @author B.Tanev
 *
 */
public class StatWeekDayActivityCommandHandler
		extends
		GenericCommandHandler<StatCommandInput, ArrayList<WeekDayActivityStat>, CommandResult<StatCommandInput, ArrayList<WeekDayActivityStat>>, StatWeekDayActivityCommand> {

	private final TargetService targetService;
	private final AnalyticsService analyticsService;

	public StatWeekDayActivityCommandHandler(TargetService targetService, AnalyticsService analyticsService) {
		super();

		Validate.notNull(targetService);
		Validate.notNull(analyticsService);

		this.targetService = targetService;
		this.analyticsService = analyticsService;
	}

	@Override
	protected ArrayList<WeekDayActivityStat> doExecuteInternal(StatCommandInput attachedInput) {
		Validate.notNull(attachedInput);

		TargetDto targetInput = attachedInput.getTargetDto();
		Validate.notNull(targetInput);

		Long targetId = targetInput.getId();
		Validate.notNull(targetId);
		Validate.isTrue(targetId.longValue() > 0);

		List<WeekDayActivityStat> weekDayStats = null;
		Target target = targetService.findByIdentifier(targetId);
		if (target != null) {
			weekDayStats = analyticsService.findWeekDayActivity(target, attachedInput.getBeginDate(), attachedInput
					.getEndDate());
		}

		return (ArrayList<WeekDayActivityStat>) weekDayStats;
	}

	@Override
	protected CommandResult<StatCommandInput, ArrayList<WeekDayActivityStat>> packCommandResult(StatCommandInput input,
			ArrayList<WeekDayActivityStat> detachedResult) {

		return new CommandResult<StatCommandInput, ArrayList<WeekDayActivityStat>>(input, detachedResult);
	}

	@Override
	public StatCommandInput attach(StatCommandInput input) {
		return input;
	}

	@Override
	public ArrayList<WeekDayActivityStat> detach(ArrayList<WeekDayActivityStat> result) {
		return result;
	}

}
